import LRUCache from 'lru-cache'
import buildSortedURL from './buildSortedURL'
import md5 from 'md5'

const FIVE_MINUTES = 1000 * 60 * 5
const CAPACITY = 100

export default function cacheAdapter (adapter, options = {}) {
  const {
		enabledByDefault = true,
		cacheFlag = 'cache',
		defaultCache = new LRUCache({ maxAge: FIVE_MINUTES, max: CAPACITY })
  } = options
  
  return config => {
    const { url, method, params, paramsSerializer, data } = config
    const _params = params || data || {}
    const useCache = _params[cacheFlag]!== undefined ? _params[cacheFlag] : enabledByDefault
    if (method === 'get' && useCache) {
      const index = buildSortedURL(url, params, paramsSerializer)
      let key = md5(index)
      let responsePromise = defaultCache.get(key)
      if (!responsePromise) {
        responsePromise = (async () => {
          try {
            const result =  await adapter(config)
            return result
          } catch (reason) {
            defaultCache.del(key)
            throw reason
          }
        })()
        defaultCache.set(key, responsePromise)
      }
      if (process.env.LOGGER_LEVEL === 'info') {
        // eslint-disable-next-line no-console
        console.info(`[axios-cache-adapter] request cached by cache adapter --> url: ${index}`)
      }
      return responsePromise
    }
    return adapter(config)
  }
}
